//
//  HYBaseHttpTools.m
//  广告页
//
//  Created by YYY on 2017/2/17.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

#import "HYBaseHttpTools.h"

#import "AFURLSessionManager.h"
#import "AFHTTPSessionManager.h"
#import "AFNetworkActivityIndicatorManager.h"

#import <CommonCrypto/CommonDigest.h>

/*本地化存储*/
#define myDefaults [NSUserDefaults standardUserDefaults]

static CurrentNetworkStatus my_networkStatus = NetworkStatusReachableViaWiFi;

@implementation HYBaseHttpTools

+(HYBaseHttpTools *)shareHYBaseHttpTools
{
    static HYBaseHttpTools *sharedBaseHttpTools = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedBaseHttpTools = [[HYBaseHttpTools alloc]init];
    });
    return sharedBaseHttpTools;
}


#pragma mark --- 网络连接状态
-(void)detectNetwork
{
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [reachabilityManager startMonitoring];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
         if (status == AFNetworkReachabilityStatusNotReachable)
         {
             my_networkStatus = NetworkStatusNotReachable;
         }
         else if (status == AFNetworkReachabilityStatusUnknown)
         {
             my_networkStatus = NetworkStatusUnknown;
         }
         else if (status == AFNetworkReachabilityStatusReachableViaWWAN)
         {
             my_networkStatus = NetworkStatusReachableViaWWAN;
         }
         else if (status == AFNetworkReachabilityStatusReachableViaWiFi)
         {
             my_networkStatus = NetworkStatusReachableViaWiFi;
         }
     }];
}

/*网络请求*/
-(void)commonInterfaceRequestHttpToolPostConvertList:(NSMutableDictionary *)parameters urlString:(NSString *)urlString success:(NetworkRequestSuccess)success fail:(NetworkRequestFail)fail
{
    //判断网络状态
    [self detectNetwork];
    //没有网络时不执行请求
    if(my_networkStatus == NetworkStatusNotReachable || my_networkStatus == NetworkStatusUnknown)
    {
        //断网提示,直接走请求失败回调,--解决了在断网时点击登录按钮,按钮交互关闭,在请求失败的回调中开启按钮交互
        NSError *erro = [[NSError alloc]initWithDomain:@"NSURLErrorDomain" code:MAXFLOAT userInfo:@{ @"NSLocalizedDescription":@"当前网络不可用，请检测网络"}];
        fail(erro);
        return;
    }
    /*
     dispatch_async开启一个异步操作，第一个参数是指定一个gcd队列，第二个参数是分配一个处理事物的程序块到该队列。
     dispatch_get_global_queue(0, 0)，指用了全局队列。
     */
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //处理耗时操作的代码块..
        [[HYBaseHttpTools shareHYBaseHttpTools] postUrl:urlString withDict:parameters sucess:^(NSDictionary *responseObject)
         {
             if (success)
             {
                 success(responseObject);
             }
         } fail:^(NSError *error)
         {
             if (fail)
             {
                 fail(error);
             }
         }];
    });
}

- (void)postUrl:(NSString *)url withDict:(NSMutableDictionary * )parameters sucess:(NetworkRequestSuccess)sucess fail:(NetworkRequestFail)fail
{
    AFHTTPSessionManager *manager = [self manager];

    NSString *userAgents = @"ZHUMENGYUNSHOPMALLIOS/1.3.0/iPhone 6 Plus/iOS/10.1.1";
    NSString *authorization = [myDefaults objectForKey:@"authorization"];
    if (userAgents.length != 0)
    {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",userAgents] forHTTPHeaderField:@"user-agents"];
    }
    if (authorization.length != 0)
    {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[myDefaults objectForKey:@"authorization"]] forHTTPHeaderField:@"authorization"];
    }
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
               {
                   
               } progress:^(NSProgress * _Nonnull uploadProgress)
               {
                   
               } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
               {
                   if (sucess)
                   {
                       sucess(responseObject);
                   }
               } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
               {
                   if (fail)
                   {
                       fail(error);
                   }
               }];
}

#pragma mark --- 初始化AFHTTPSessionManager
- (AFHTTPSessionManager *)manager
{
    AFHTTPSessionManager *manager = nil;
    // 开启转圈圈
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    manager = [AFHTTPSessionManager manager];
    
    //manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*"]];
    
    //请求超时时间
    manager.requestSerializer.timeoutInterval = 10;
    
    // 设置允许同时最大并发数量，过大容易出问题
    manager.operationQueue.maxConcurrentOperationCount = 3;
    
    return manager;
}

@end
